import React from 'react';
import dynamic from 'dva/dynamic';
import { Router } from 'dva/router';
import { renderRoutes } from 'react-router-config';
import routes from './config/route';

function RouterConfig({ history, app }) {
  return (
    <Router history={history}>
      {renderRoutes(routes.reduce((a, r) => [...a, ...transRoutes(r, ['app'], app)], []))}
    </Router>
  );
}

// 因为 react-router-config 要求父子组件必须嵌套 route
// 但是, 本应用的父子组件只表示业务关系，组件之间是平级的, 所有有个展平的操作
function transRoutes(route, models = [], app) {
  // name, label, models 属于自定义属性, 会被丢弃
  const { name, label, models: mds = [], component: comp, routes: rts, ...rest } = route; // eslint-disable-line
  const allModels = models.concat(mds);

  const component = dynamic({
    app,
    models: () => allModels.map(m => import(`./models/${m}`)),
    component: comp,
  });

  const routes = rts && rts.length ? rts.reduce((a, r) => [...a, ...transRoutes(r, allModels, app)], []) : []; // eslint-disable-line

  return [{ ...rest, component }, ...routes];
}

export default RouterConfig;
